package assists
{
	import assists.log.Log;
	
	import xmlS.LangXMLLoader;
	
	public class Lang
	{
		private static const PREFIX_TAG:String = '{!';
		private static const SUFFIX_TAG:String = '}';
		
		private static var xmlData:XML;
		private var _loader:LangXMLLoader;
		
		private var _CompleteCallBack:Function;
		
		public function Lang(loader:LangXMLLoader)
		{
			_loader = loader;
		}
		
		public function initThis(completeCallBack:Function):void
		{
			if(xmlData == null){
				xmlData = new XML();
				_CompleteCallBack = completeCallBack;
				_loader.loadXml("assets/designXML/ClientLang.xml",saveData);
			}
		}
		
		private function saveData(xml:XML):void
		{
			xmlData = xml;
			if(_CompleteCallBack is Function){
				_CompleteCallBack();
			}
		}
		
		public function client(key:*, replacePairs:Object=null) : String
		{
			return getLang(key, replacePairs);	
		}
		
		private function getLang(key:*, replacePairs:Object=null) : String
		{
			if(xmlData != null){
				var langStr:String = xmlData[key];
				if(xmlData[key]){
					if (replacePairs != null) {
						langStr = format(langStr, replacePairs);
					}
					return langStr;
				}else{
					return "";
				}
			}else{
				return "";	
			}
			return "";
		}
		
		private static function format(source:String, pairs:Object) : String
		{
			var langPairs:Object = {};
			for (var src:String in pairs) {
				langPairs[PREFIX_TAG + src + SUFFIX_TAG] = pairs[src];
			}
			return replace(source, langPairs);
		}
		
		public static function replace(source:String, pairs:Object) : String
		{
			var dest:String = source;
			for (var src:String in pairs) {		
				dest = dest.replace(new RegExp(src, "g"), pairs[src]);	
			}
			return dest;			
		}
	}
}